package com.maxlen.ware.listener;

import com.alibaba.fastjson.JSONObject;
import com.maxlen.common.rabbitMQConstant.WareRabbitMQConstant;
import com.maxlen.ware.entity.WareOrderTaskDetailEntity;
import com.maxlen.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;

@Slf4j
@Component
@RabbitListener(queues = WareRabbitMQConstant.WARE_STOCK_RELEASE_QUEUE)
public class WareStockRabbitListener {

    @Autowired
    private WareSkuService wareSkuService;

    @RabbitHandler
    public void wareStockReleaseQueue(Long wareOrderTaskDetailId, @Headers Message headers, Channel channel) throws IOException {
        log.info("开始通过库存订单任务详情表id: {} 解锁库存 ", wareOrderTaskDetailId);
        try{
            wareSkuService.isUnlockStock(wareOrderTaskDetailId);
            channel.basicAck(headers.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            log.info(e.getMessage());
            channel.basicReject(headers.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void wareStockReleaseQueue(byte[] orderSn, @Headers Message headers, Channel channel) throws IOException {
        log.info("订单取消, 通过订单号: {} 解锁库存.....", new String(orderSn));
        try{
            wareSkuService.isUnlockStock(orderSn);
            channel.basicAck(headers.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            log.info(e.getMessage());
            channel.basicReject(headers.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
